<template>
  <div ref="videoContainer" class="video-container"></div>
</template>
<script setup>
import { onMounted, watch } from "vue";

import Player from "xgplayer";
import "xgplayer/dist/index.min.css";
// props
// 视频地址
const props = defineProps({
  url: {
    type: String,
    default: "",
  },
});
const videoContainer = ref(null);
let player = null;
const initializePlayer = (url) => {
  if (player) {
    player.destroy(); // 销毁现有播放器实例
  }
  player = new Player({
    el: videoContainer.value,
    url: url,
    autoplay: false,
    lang: "zh",
    screenShot: true,
    fluid: true,
  });
};

onMounted(() => {
  initializePlayer(props.url);
});

watch(
  () => props.url,
  (newUrl) => {
    if (player) {
      player.src = newUrl; // 直接更改播放器的 src 属性
      // player.play(); // 播放新视频
    } else {
      initializePlayer(newUrl);
    }
  }
);

onBeforeUnmount(() => {
  if (player) {
    player.destroy();
  }
});
</script>

<style scoped>
.video-container {
  flex: auto;
}
</style>
